# 定时任务调度器
# 负责定时任务的注册和管理。

import logging
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import pytz

from .upload_drug_info_task import upload_drug_info_job
from core.logger import init_logger

# --- 日志配置 ---
init_logger()
logger = logging.getLogger(__name__)

# 全局调度器
_scheduler = None


def init_scheduler():
    # 初始化调度器
    global _scheduler
    
    if _scheduler is not None:
        return _scheduler
    
    _scheduler = BackgroundScheduler(
        timezone=pytz.timezone('Asia/Shanghai')
    )
    
    # 注册药品信息上传任务 - 每天凌晨2点执行 (cron: "0 2 * * *")
    _scheduler.add_job(
        func=upload_drug_info_job,
        trigger=CronTrigger.from_crontab("0 2 * * *"),
        id='upload_drug_info',
        name='药品信息上传任务',
        replace_existing=True
    )
    
    logger.info("定时任务调度器初始化完成")
    logger.info("时区: Asia/Shanghai")
    logger.info("已注册任务:")
    logger.info("  - 药品信息上传任务 (每天凌晨2点)")
    
    return _scheduler


def start_scheduler():
    # 启动调度器
    global _scheduler
    
    if _scheduler is None:
        init_scheduler()
    
    _scheduler.start()
    logger.info("定时任务调度器已启动")


def stop_scheduler():
    # 停止调度器
    global _scheduler
    
    if _scheduler and _scheduler.running:
        _scheduler.shutdown()
        logger.info("定时任务调度器已停止")


def get_scheduler():
    # 获取调度器实例
    if _scheduler is None:
        init_scheduler()
    return _scheduler
